package com.blogs.service;


import android.content.Context;

import com.blogs.entity.AppConfig;
import com.blogs.entity.AppEnums;
import com.blogs.entity.MsgEntity;
import com.blogs.tools.TbBlogLine;
import com.blogs.tools.TbContent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GetBlogDetail {
	public interface IMsgCallBack {
		public void onSuccess(String result);
		public void onFailed();
	}
	private TbContent db;
	private String blog_url=AppConfig.GETBLOGDETAIL_URL;
	private String new_url=AppConfig.GETNEWDETAIL_URL;
	private String search_blog_url=AppConfig.GET_CONTENT_FROM_SEARCH;
	private String url="";
	private IMsgCallBack callback;
	private GetMsgTask blogContentTask;
	public GetBlogDetail(Context context,int type, String id,IMsgCallBack callback)
	{
		this.callback=callback;
		if(type==AppEnums.EnumContentType.blog)
		{
			url+=blog_url.replace("{0}", id);
		}
		else if(type==AppEnums.EnumContentType.news)
		{
			url+=new_url.replace("{0}", id);
		}
		else if(type==AppEnums.EnumContentType.search_blog_detail)
		{
			url+=search_blog_url.replace("{0}", id);
		}
		blogContentTask=new GetMsgTask(taskCallBack);
		if(type==AppEnums.EnumContentType.search_blog_detail)
			return;
		db=new TbContent(context, id.trim());
	}
	public void loadData()
	{
		if(db!=null&&db.RowCount()>0)
		{
			callback.onSuccess(db.Select());
			db.DbClose();
		}
		else
		{
			blogContentTask.execute(url);
		}
		
	}
	private GetMsgTask.onTaskCallBack taskCallBack=new GetMsgTask.onTaskCallBack() {
		
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			
			GsonBuilder builder = new GsonBuilder();
			Gson gson = builder.create();
			MsgEntity<Object> msg=null;
			try
			{
				msg=gson.fromJson(result,MsgEntity.class);
			}
			catch(Exception e)
			{
				callback.onFailed();
				if(db!=null)
				{
					db.DbClose();
				}
				return;
			}
			if(msg.op.equals(""))
			{
				callback.onFailed();
				if(db!=null)
				{
					db.DbClose();
				} 
				return;
			}
			String con=(String) msg.data;
			if(con==null)
			{
				con="";
			}
			if(db!=null)
			{
				db.Insert(con);
				db.DbClose();
			}
			callback.onSuccess(con);
		}
		
		public void onFailed() {
			// TODO Auto-generated method stub
			callback.onFailed();
			if(db!=null)
			{
				db.DbClose();
			}
		}
	};
}
